//
// Created by 紫霄 on 2020/4/18.
//

#ifndef LEETCODE_29_H
#define LEETCODE_29_H
/*
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。

 

示例 1：

输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[1,2,3,6,9,8,7,4,5]
示例 2：

输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 *
 *
 */

#include <vector>
using namespace std;
class Solution {
public:
  vector<int> spiralOrder(vector<vector<int>> &matrix) {
    vector<int> ans;
    if (!matrix.empty()) {
      size_t row = matrix.size();
      size_t col = matrix[0].size();
      int leftBegin = 0;
      int topBegin = 0;
      int curRow = 0, curCol = 0;
      while (((row - topBegin) > 0) && ((col - leftBegin) > 0)) {
        if ((row - topBegin) == 1) {
          for (; curCol < col; ++curCol) {
            ans.push_back(matrix[curRow][curCol]);
          }
          return ans;
        } else if ((col - leftBegin) == 1) {
          for (; curRow < row; ++curRow) {
            ans.push_back(matrix[curRow][curCol]);
          }
          return ans;
        } else {
          for (; curCol < col; ++curCol) {
            ans.push_back(matrix[curRow][curCol]);
          }
          ++topBegin;
          --curCol;
          ++curRow;
          for (; curRow < row; ++curRow) {
            ans.push_back(matrix[curRow][curCol]);
          }
          --curRow;
          --curCol;
          for (; (curCol > leftBegin - 1); --curCol) {
            ans.push_back(matrix[curRow][curCol]);
          }
          ++curCol;
          --curRow;
          ++leftBegin;
          for (; (curRow > topBegin - 1); --curRow) {
            ans.push_back(matrix[curRow][curCol]);
          }
          ++curRow;
          ++curCol;
        }
        --row;
        --col;
      }
    }
    return ans;
  }
};
#endif // LEETCODE_29_H
